<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>实现复选框的全选、反选和全不选操作</title>
<style>
body{
font-family:微软雅黑}
</style>
<script src="../JS/vue.js"></script>
</head>
<body>
<div id="example">
	<input type="checkbox" value="上网" v-model="checkedNames">
	<label for="net">上网</label>
	<input type="checkbox" value="旅游" v-model="checkedNames">
	<label for="tourism">旅游</label>
	<input type="checkbox" value="看书" v-model="checkedNames">
	<label for="book">看书</label>
	<input type="checkbox" value="电影" v-model="checkedNames">
	<label for="movie">电影</label>
	<input type="checkbox" value="游戏" v-model="checkedNames">
	<label for="game">游戏</label>
	<p v-if="checked">
		您的兴趣爱好：{{result}}
	</p>
	<p>
		<button @click="allChecked">全选</button>
		<button @click="reverseChecked">反选</button>
		<button @click="noChecked">全不选</button>
	</p>
</div>
<script type="text/javascript">
var exam = new Vue({
	el: '#example',
	data: {
		checked: false,
		checkedNames: [],
		checkedArr: ["上网", "旅游", "看书", "电影", "游戏"],
		tempArr: []
	},
	methods: {
		allChecked: function() {//全选
			this.checkedNames = this.checkedArr;
		},
		noChecked: function() {//全不选
			this.checkedNames = [];
		},
		reverseChecked: function() {//反选
			this.tempArr=[];
			for(var i=0;i<this.checkedArr.length;i++){
				if(!this.checkedNames.includes(this.checkedArr[i])){
					this.tempArr.push(this.checkedArr[i]);
				}
			}
			this.checkedNames=this.tempArr;
		}
	},
	computed: {
		result: function(){//获取选中的兴趣爱好
			var show = "";
			for(var i=0;i<this.checkedNames.length;i++){
				show += this.checkedNames[i] + " ";
			}
			return show;
		}
	},
	watch: {
		"checkedNames": function() {
			if (this.checkedNames.length > 0) {
				this.checked = true//显示兴趣爱好
			} else {
				this.checked = false//隐藏兴趣爱好
			}
		}
	}
})
</script>


</body>

</html>



